<?php

class QueueController extends Controller
{
	public $layout = 'awt-presenter';
	
	public function actionIndex()
	{
		$this->render('index');
	}

	# add song to queue
	public function actionAdd($id=null) {
		
		$model = new Song();
		
		if ( !empty($_POST) && isset($_POST['Song']) ) {
			
			$id = $_POST['Song']['id'];
			$song = $model->findByAttributes(array('id'=>$id));
			
			if ($song) {
				
				$rs = PresenterInterface::create($song->id,Yii::app()->user->id);
				
				if ($rs) {
					Yii::app()->user->setFlash('success',"You have borrow WM".str_pad($id,3,'0',STR_PAD_LEFT));
					$this->redirect(array('history'));
				} else {
					Yii::app()->user->setFlash('error','WM'.str_pad($id,3,'0',STR_PAD_LEFT)." is not available for borrowed");
				}
			} else {
				$code = 'WM'.str_pad($rs->id,3,'0',STR_PAD_LEFT);
				Yii::app()->user->setFlash('error',"$code Not found");
			}
			
			$this->refresh();
		}
		
		if ($id!==null) $model->id = str_pad($id,3,'0',STR_PAD_LEFT);
		$this->render('create',array(
			'model'=>$model,
		));
	}
	
	# delete song from queue
	public function actionDelete($id=null) {
		
		$model = new Song();
		
		if ( !empty($_POST) && isset($_POST['Song']) ) {
			
			$id = $_POST['Song']['id'];
			$song = $model->findByAttributes(array('id'=>$id));
			
			if ($song) {
				
				$rs = PresenterInterface::update($song->id,Yii::app()->user->id);
				
				if ($rs) {
					Yii::app()->user->setFlash('success',"You have return WM".str_pad($id,3,'0',STR_PAD_LEFT));
					$this->redirect(array('default/history'));
				} else {
					Yii::app()->user->setFlash('error','WM'.str_pad($id,3,'0',STR_PAD_LEFT)." is not borrowed");
				}
			} else {
				$code = 'WM'.str_pad($rs->id,3,'0',STR_PAD_LEFT);
				Yii::app()->user->setFlash('error',"$code Not found");
			}
			
			$this->refresh();
		}
		
		if ($id!==null) $model->id = str_pad($id,3,'0',STR_PAD_LEFT);
		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	# clear queue
	public function actionClear() {
		
	}
	
	# queue view
	public function actionView() {
		
		$model = new Song();
		$rs = PresenterInterface::query(array(
			'user_id'=>Yii::app()->user->id,
		));
		
		if ( !empty($_POST) && isset($_POST['Song']) ) {
			$song = $model->findByAttributes(array('code'=>$code));
			if ($song) {
				
				$rs = PresenterInterface::update($song->id,Yii::app()->user->id);
				if ($rs) {
					Yii::app()->user->setFlash('success',"You have return a book");
					$this->redirect('presenter/default/history');
				} else {
					Yii::app()->user->setFlash('error',"This Book is not borrowed");
				}
			}
		}
		$this->render('history',array(
			'model'	=>$model,
			'rs'	=>$rs,
		));
	}
	
}

?>